import { Calendar } from '@nutui/nutui-react-taro';
import dayjs, { type Dayjs } from 'dayjs';
import { useMemo, useState } from 'react';
import { Text, View } from '@tarojs/components';
import classnames from 'classnames';
import type { CalendarProps } from '@nutui/nutui-react-taro';
import type { FC } from 'react';

import { Calendar as CalendarIcon } from '@nutui/icons-react-taro';

import { DATE_FORMAT } from '@/constants';

import './index.scss';
/**
 * @example ["2024", "06", "27", "2024/06/27", "星期四"]
 */
export type DateType = [string, string, string, string, string];

export type ValueType = [Dayjs | undefined, Dayjs | undefined];

const PREFIX_CLS = 'm-calendar-select';

interface CalendarSelectProps
  extends Partial<Omit<CalendarProps, 'type' | 'value'>> {
  className?: string;
  format?: string;
  value?: ValueType;
  onChange?: (value?: ValueType) => void;
  isTabbar?: boolean;
  showIcon?: boolean;
  // 新增：可见性回调
  onVisibleChange?: (visible: boolean) => void;
  onPopupOpen?: () => void;
  onPopupClose?: () => void;
}

const CalendarSelect: FC<CalendarSelectProps> = ({
  className,
  format = DATE_FORMAT,
  value = [],
  onChange,
  isTabbar,
  showIcon,
  onVisibleChange,
  onPopupOpen,
  onPopupClose,
  ...rest
}) => {
  const [visible, setVisible] = useState<boolean>(false);

  const _value = useMemo(() => {
    return (value as Dayjs[])
      ?.filter(Boolean)
      ?.map((item) => item.format(format));
  }, [value]);

  const handleOpen = () => {
    setVisible(true);
    onVisibleChange?.(true);
    onPopupOpen?.();
  };

  const handleClose = () => {
    setVisible(false);
    onVisibleChange?.(false);
    onPopupClose?.();
    // 透传给外部的 onClose（若存在）
    (rest as any)?.onClose?.();
  };

  return (
    <View
      className={classnames(PREFIX_CLS, className, {
        [PREFIX_CLS + '-tabbar']: isTabbar,
      })}
    >
      <View className="filter" onClick={handleOpen}>
        <View className="content">
          <View className="date">
            <View className="dateItem">
              {value?.[0]?.format(format) || (
                <Text style={{ color: '#c7c7c7' }}>开始日期</Text>
              )}
            </View>
            <View className="separator">~</View>
            <View className="dateItem">
              {value?.[1]?.format(format) || (
                <Text style={{ color: '#c7c7c7' }}>结束日期</Text>
              )}
            </View>
          </View>
          {showIcon && (
            <View className="icon">
              <CalendarIcon color="#959595" size={14} />
            </View>
          )}
        </View>
      </View>
      <Calendar
        visible={visible}
        type="range"
        defaultValue={_value}
        startDate="2000-01-01"
        endDate="2099-12-31"
        onConfirm={(v) => {
          const [start, end] = v;
          if (!(start?.length || end?.length)) {
            onChange?.();
            return;
          }
          const _start = dayjs()
            .year(Number(start[0]))
            .month(Number(start[1]) - 1)
            .date(Number(start[2]))
            .startOf('day');
          const _end = dayjs()
            .year(Number(end[0]))
            .month(Number(end[1]) - 1)
            .date(Number(end[2]))
            .endOf('day');
          onChange?.([_start, _end]);
        }}
        onClose={handleClose}
        {...rest}
      />
    </View>
  );
};

export default CalendarSelect;
